package ui.panel;

import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.KeyStroke;

import security.auth.UserManager;
import session.Session;
import ui.AdminCreateUserDialog;
import ui.MainFrame;

/**
     * 创建菜单栏，包含文件、编辑、数据库、运行和帮助菜单
     */
public class MenuBarCreator {
    private final MainFrame mainFrame;

    public MenuBarCreator(MainFrame mainFrame) {
        this.mainFrame = mainFrame;
    }

    public JMenuBar createMenuBar() {
        JMenuBar menuBar = new JMenuBar();

        // 文件菜单
        JMenu fileMenu = new JMenu("文件");
        JMenuItem newItem = new JMenuItem("新建标签页");
        JMenuItem openItem = new JMenuItem("打开");
        JMenuItem saveItem = new JMenuItem("保存当前页");
        JMenuItem saveAsItem = new JMenuItem("另存为");

        newItem.addActionListener(e -> mainFrame.addNewTab());
        openItem.addActionListener(e -> mainFrame.openSQLFile());
        saveItem.addActionListener(e -> mainFrame.saveSQLToFile());
        saveAsItem.addActionListener(e -> mainFrame.saveSQLToFile(true));

        fileMenu.add(newItem);
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.add(saveAsItem);

        fileMenu.addSeparator();

        // 创建独立的登出菜单
        JMenu logoutMenu = new JMenu("登出");
        JMenuItem logoutItem = new JMenuItem("登出");
        logoutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK));
        logoutItem.addActionListener(e -> {
            // 执行登出逻辑
            if (mainFrame != null) {
                Session currentSession = Session.getCurrentSession();
                if (currentSession != null) {
                    String username = currentSession.getUsername();
                    UserManager.logout(currentSession);
                    JOptionPane.showMessageDialog(mainFrame,
                        "用户 " + username + " 已登出",
                        "登出成功",
                        JOptionPane.INFORMATION_MESSAGE);

                    // 关闭当前窗口，返回登录界面
                    mainFrame.dispose();
                    new ui.LoginFrame();
                }
            }
        });
        logoutMenu.add(logoutItem);

        fileMenu.addSeparator();

        // 编辑菜单
        JMenu editMenu = new JMenu("编辑");
        JMenuItem undoItem = new JMenuItem("撤销");
        JMenuItem redoItem = new JMenuItem("重做");
        JMenuItem findItem = new JMenuItem("查找/替换");

        // 为编辑菜单项添加事件监听器
        undoItem.addActionListener(e -> {
            int index = mainFrame.getSqlTabbedPane().getSelectedIndex();
            if (index >= 0 && index < mainFrame.getSqlEditors().size()) {
                if (mainFrame.getSqlEditors().get(index).canUndo()) {
                    mainFrame.getSqlEditors().get(index).undoLastAction();
                }
            }
        });

        redoItem.addActionListener(e -> {
            int index = mainFrame.getSqlTabbedPane().getSelectedIndex();
            if (index >= 0 && index < mainFrame.getSqlEditors().size()) {
                if (mainFrame.getSqlEditors().get(index).canRedo()) {
                    mainFrame.getSqlEditors().get(index).redoLastAction();
                }
            }
        });

        findItem.addActionListener(e -> mainFrame.showFindReplaceDialog());

        editMenu.add(undoItem);
        editMenu.add(redoItem);
        editMenu.add(new JSeparator());
        editMenu.add(findItem);

        // 数据库菜单
        JMenu dbMenu = new JMenu("数据库");
        JMenuItem connectItem = new JMenuItem("连接");
        JMenuItem switchItem = new JMenuItem("切换");
        JMenuItem refreshItem = new JMenuItem("刷新");

        connectItem.addActionListener(e -> mainFrame.connectDatabase());
        switchItem.addActionListener(e -> mainFrame.switchDatabase());
        refreshItem.addActionListener(e -> mainFrame.refreshDatabaseList());

        dbMenu.add(connectItem);
        dbMenu.add(switchItem);
        dbMenu.add(refreshItem);


        // 新增命令窗口菜单
        JMenu commandWindowMenu = new JMenu("命令窗口");

        // 显示/隐藏命令窗口菜单项
        JMenuItem showCommandWindowItem = new JMenuItem("显示/隐藏命令窗口");
        showCommandWindowItem.addActionListener(e -> mainFrame.toggleCommandWindow());
        commandWindowMenu.add(showCommandWindowItem);


        menuBar.add(commandWindowMenu);



        // 运行菜单
        JMenu runMenu = new JMenu("运行");
        JMenuItem execItem = new JMenuItem("执行 SQL (Ctrl+Enter)");
        JMenuItem execSelectedItem = new JMenuItem("执行选中 SQL");
        JMenuItem execAndCommitItem = new JMenuItem("执行并提交");
        JMenuItem formatItem = new JMenuItem("格式化 SQL");

        execItem.addActionListener(e -> mainFrame.executeSQL());
        execSelectedItem.addActionListener(e -> mainFrame.executeSelectedSQL());
        execAndCommitItem.addActionListener(e -> mainFrame.executeAndCommit());
        formatItem.addActionListener(e -> mainFrame.formatSQL());

        runMenu.add(execItem);
        runMenu.add(execSelectedItem);
        runMenu.add(execAndCommitItem);
        runMenu.add(new JSeparator());
        runMenu.add(formatItem);

        // 用户管理菜单 (仅管理员可见)
        JMenu userMenu = new JMenu("用户管理");
        JMenuItem createUserItem = new JMenuItem("创建用户");
        createUserItem.addActionListener(e -> {
            Session currentSession = Session.getCurrentSession();
            if (currentSession != null && currentSession.getUserLevel() == UserManager.ADMIN_LEVEL) {
                new AdminCreateUserDialog(mainFrame);
            } else {
                JOptionPane.showMessageDialog(mainFrame,
                    "只有管理员可以创建用户",
                    "权限不足",
                    JOptionPane.WARNING_MESSAGE);
            }
        });
        userMenu.add(createUserItem);

        // 帮助菜单
        JMenu helpMenu = new JMenu("帮助");
        JMenuItem aboutItem = new JMenuItem("关于");
        JMenuItem shortcutItem = new JMenuItem("快捷键");
        JMenuItem docsItem = new JMenuItem("文档");

        aboutItem.addActionListener(e -> mainFrame.showAboutDialog());
        shortcutItem.addActionListener(e -> mainFrame.showShortcutDialog());
        docsItem.addActionListener(e -> mainFrame.showDocumentation());

        helpMenu.add(aboutItem);
        helpMenu.add(shortcutItem);
        helpMenu.add(docsItem);

        // 添加所有菜单项到菜单栏
        menuBar.add(fileMenu);
        menuBar.add(editMenu);
        menuBar.add(dbMenu);
        menuBar.add(runMenu);
        menuBar.add(userMenu);
        menuBar.add(logoutMenu);
        menuBar.add(helpMenu);

        // 根据用户权限设置菜单可见性
        Session currentSession = Session.getCurrentSession();
        userMenu.setVisible(currentSession != null && currentSession.getUserLevel() == UserManager.ADMIN_LEVEL);

        return menuBar;
    }
}